package cn.edu.nju.software;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class SendMessage {
	private int type;
	private String IP;
	private String filePath;
	private String fromServer;
	private Socket socket;
	
	
	public SendMessage(int type, String IP, String filePath, String fromServer) {
		this.type = type;
		this.IP = IP;
		this.filePath = filePath;
		this.fromServer = fromServer;
		sendMessage();
	}

	private void sendMessage() {
		// TODO Auto-generated method stub
		
		try {
			socket = new Socket(IP, 8000);
			
			DataInputStream inputStream = new DataInputStream(
					new BufferedInputStream(new FileInputStream(filePath)));
			DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
			
			int bufferSize = 8192;
			byte[] buf = new byte[bufferSize];
			
			outputStream.writeInt(type);
			outputStream.writeUTF(fromServer);
			
			while(true) {
				int read = 0;
				if (inputStream != null) {
					read = inputStream.read(buf);
				}
				if (read == -1)
					break;
				
				outputStream.write(buf, 0, read);
			}
			outputStream.flush();
			
			inputStream.close();
			outputStream.close();
			System.out.println("The file thansfered to target server finished!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
